import type { CategoryItem } from '@/indexDB/index'
import type { HoldItem } from '@/indexDB/initHold'
import { buildCategoryTree } from '@/views/category/buildCategoryTree'

const getHoldCategoryList = (categoryList: CategoryItem[], holdList: HoldItem[]) => {

  return categoryList.map(category => {
    const { id, level } = category
    const value = holdList.filter(hold => hold.categoryId === id).reduce((lastValue, curHold) => {
      const { holdValue } = curHold
      return +(lastValue + Number(holdValue)).toFixed(4)
    }, 0)
    if (level === 3) {
      return {
        ...category,
        value
      }
    } else {
      return category
    }

  })
}

self.addEventListener('message', e => {
  const { holdList, categoryList } = JSON.parse(e.data)
  const holdCategoryList = getHoldCategoryList(categoryList, holdList)
  const tree = buildCategoryTree(holdCategoryList)
  postMessage(tree)
})